package com.demo.springboot;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

@Repository
public class TagDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public void addTag(String name, String description, int status) {
        String sql = "insert into tag(tag_name,tag_description,tag_status)values('" + name + "','" + description + "',"
            + status + ");";
        jdbcTemplate.execute(sql);
    }

    /**
     * rollbackFor 设置哪些异常时事务进行回滚。
     * noRollbackFor 设置哪些异常时事务不回滚。
     */
    @Transactional(rollbackFor = Exception.class)
    public void addTagBatch(String description, int status, String... names) {
        for (String name : names) {
            String sql = "insert into tag(tag_description,tag_status,tag_name)values('" + description + "'," + status + ",'"
                + name + "');";
            jdbcTemplate.execute(sql);

            if(true){
                //throw new NullPointerException("异常，数据库要回滚");
            }
        }
    }
}
